package com.gla.market.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gla.market.R;
import com.gla.market.adapter.AfterSearchAdapter;
import com.gla.market.adapter.FYH_CommodityAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Commodity;
import com.gla.market.entity.ShopItem;
import com.gla.market.utils.NetUtil;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AfterSearchActivity extends AppCompatActivity implements View.OnClickListener, TencentLocationListener {

    private TextView in; //最顶上搜索框，不可编辑，点击跳转搜索前页面
    private TextView pet,petgoods,all; //搜索框下导航栏
    private GridView item_list;  //适配器名字
    List<ShopItem> shopItemList = new ArrayList<>();  //适配器里的数据
    List<Commodity> commodityList = new ArrayList<>();

    private AfterSearchAdapter shop_item_adapter; //适配器对象
    private FYH_CommodityAdapter commodity_item_adapter;

    Double La,Lo; //经纬度
    String keyword; //查询的关键词

    //用于从网络初始化UI的handler
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(AfterSearchActivity.this, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(AfterSearchActivity.this, msg.obj == null ? "请求数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    System.out.println(shopItemList);
                    //监听适配器列表
                    item_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            ShopItem shopItem = shopItemList.get(position);
                            Integer shop_id = shopItem.getId();
                            Intent intent = new Intent(AfterSearchActivity.this, Shop_FYHActivity.class);
                            intent.putExtra("id",shop_id + "");
                            startActivity(intent);
                        }
                    });
                    //成功调用，到adapter赋值
                    shop_item_adapter = new AfterSearchAdapter(AfterSearchActivity.this,shopItemList,La,Lo);
                    item_list.setAdapter(shop_item_adapter);
                    break;
                case 3:
                    //监听适配器列表
                    item_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Commodity commodity = commodityList.get(position);
                            Integer commodityId = commodity.getId();
                            Intent intent = new Intent(AfterSearchActivity.this, Commodity_FYHActivity.class);
                            intent.putExtra("id",commodityId + "");
                            startActivity(intent);
                        }
                    });
                    commodity_item_adapter = new FYH_CommodityAdapter(AfterSearchActivity.this,commodityList);
                    item_list.setAdapter(commodity_item_adapter);
                    break;
                case 4:
                    //监听适配器列表
                    item_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Commodity commodity = commodityList.get(position);
                            Integer commodityId = commodity.getId();
                            Intent intent = new Intent(AfterSearchActivity.this, Commodity_FYHActivity.class);
                            intent.putExtra("id",commodityId + "");
                            startActivity(intent);
                        }
                    });
                    commodity_item_adapter = new FYH_CommodityAdapter(AfterSearchActivity.this,commodityList);
                    item_list.setAdapter(commodity_item_adapter);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_after_search);

        //顶部搜索框
        in = findViewById(R.id.after_search_in);
        Intent intent = getIntent();
        keyword = intent.getStringExtra("keyword");
        in.setText(keyword);

        //搜索框下导航栏
        pet = findViewById(R.id.after_search_pet);
        petgoods = findViewById(R.id.after_search_petgoods);
        all = findViewById(R.id.after_search_all);
        pet.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
        petgoods.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
        all.setTextColor(ContextCompat.getColor(this, R.color.button_press));


        all.setBackgroundResource(R.drawable.after_search_bottom_line); //被触发导航栏下划线变色
        pet.setBackground(null); //未被触发导航栏下划线不变色
        petgoods.setBackground(null);
        initView(); //适配器初始化
        getLocation();

    }

    public void getLocation(){
        //获取定位,不可改动
        TencentLocationManager mLocationManager = TencentLocationManager.getInstance(this);
        mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
    }
    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        La = tencentLocation.getLatitude();
        Lo = tencentLocation.getLongitude();

        System.out.println("经纬度获取成功");
        initData("all"); //适配器数据初始化
    }
    @Override
    public void onStatusUpdate(String s, int i, String s1) { }

    //onClick监听事件
    @Override
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.after_search_back:
                finish();
                break;
            case R.id.after_search_in:
                finish();
                break;

            case R.id.after_search_pet:
                pet.setTextColor(ContextCompat.getColor(this, R.color.button_press));
                petgoods.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
                all.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
                pet.setBackgroundResource(R.drawable.after_search_bottom_line); //被触发导航栏下划线变色
                petgoods.setBackground(null); //未被触发导航栏下划线不变色
                all.setBackground(null);
                //选择属性，重新调用适配器
                shopItemList.clear();
                commodityList.clear();
                initData("pet");
                break;

            case R.id.after_search_petgoods:
                pet.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
                petgoods.setTextColor(ContextCompat.getColor(this, R.color.button_press));
                all.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
                petgoods.setBackgroundResource(R.drawable.after_search_bottom_line);
                pet.setBackground(null);
                all.setBackground(null);
                //选择属性，重新调用适配器
                shopItemList.clear();
                commodityList.clear();

                initData("petgoods");
                break;
            case R.id.after_search_all:
                pet.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
                petgoods.setTextColor(ContextCompat.getColor(this, R.color.button_normal));
                all.setTextColor(ContextCompat.getColor(this, R.color.button_press));
                all.setBackgroundResource(R.drawable.after_search_bottom_line);
                pet.setBackground(null);
                petgoods.setBackground(null);
                //未完成，查数据库
                shopItemList.clear();
                commodityList.clear();
                initData("all");
                break;
            default:
                break;
        }
    }

    //适配器初始化
    private void initView(){
            //绑定控件
            item_list = findViewById(R.id.after_search_shop_item);
    }

    //适配器数据初始化
    private void initData(String type){
        if(type == "all"){
            //调用后端，获取json数据
            String url = Constants.BASE_URL + Constants.GET_SEARCH_URL + Constants.GET_SEARCH_RESULT_SHOP +"?keyword="+keyword;
            NetUtil.doGet(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("调试", "错误信息：" + e.toString());
                            Message message = Message.obtain();
                            message.what = -1;
                            uiHandler.sendMessage(message);
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string().trim();
                            com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                            Message message = Message.obtain();

                            if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                                JSONArray array = object.getJSONArray("data");
                                //获得商品list
                                System.out.println("或取商品成功");
                                shopItemList = JSONArray.parseArray(array.toString(), ShopItem.class);
                                System.out.println(shopItemList);
                                System.out.println("赋值商品成功");
                                message.what = 2;
                            } else {
                                message.what = 0;
                            }
                            uiHandler.sendMessage(message);
                        }
                    }
            );
        }

        if(type=="pet"){
            //调用后端，获取json数据
            String url = Constants.BASE_URL + Constants.GET_SEARCH_URL + Constants.GET_SEARCH_RESULT_PET +"?keyword="+keyword;
            NetUtil.doGet(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("调试", "错误信息：" + e.toString());
                            Message message = Message.obtain();
                            message.what = -1;
                            uiHandler.sendMessage(message);
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string().trim();
                            com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                            Message message = Message.obtain();

                            if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                                JSONArray array = object.getJSONArray("data");
                                //获得商品list
                                System.out.println("或取商品成功");
                                commodityList = JSONArray.parseArray(array.toString(), Commodity.class);
                                System.out.println(commodityList);
                                System.out.println("赋值商品成功");
                                message.what = 3;
                            } else {
                                message.what = 0;
                            }
                            uiHandler.sendMessage(message);
                        }
                    }
            );
        }

        if(type=="petgoods"){
            //调用后端，获取json数据
            String url = Constants.BASE_URL + Constants.GET_SEARCH_URL + Constants.GET_SEARCH_RESULT_PETGOODS +"?keyword="+keyword;
            NetUtil.doGet(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("调试", "错误信息：" + e.toString());
                            Message message = Message.obtain();
                            message.what = -1;
                            uiHandler.sendMessage(message);
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string().trim();
                            com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                            Message message = Message.obtain();

                            if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                                JSONArray array = object.getJSONArray("data");
                                //获得商品list
                                System.out.println("或取商品成功");
                                commodityList = JSONArray.parseArray(array.toString(), Commodity.class);
                                System.out.println(commodityList);
                                System.out.println("赋值商品成功");
                                message.what = 4;
                            } else {
                                message.what = 0;
                            }
                            uiHandler.sendMessage(message);
                        }
                    }
            );

        }

    }

}